package Client;

import Util.Tool;
import org.jboss.netty.channel.*;

/**
 * @Author:AwakeningCode
 * @Date: Created in 8:47 2018\1\19 0019
 */
public class MyClientHandler extends SimpleChannelHandler{
    //连接到服务器端时，发出消息
    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("Connected to Server!");
        e.getChannel().write("from Client :Hello!" + System.currentTimeMillis());
        super.channelConnected(ctx, e);
    }

    @SuppressWarnings("static-access")
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        System.out.println("Client Received:" + e.getMessage());
        //休息随机秒后发送消息
        Thread thread = Thread.currentThread();
        int interval = Tool.getInterval(5);
        thread.sleep(interval*1000);
        e.getChannel().write("from Client:Hello! " + System.currentTimeMillis());
        super.messageReceived(ctx, e);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        e.getCause().printStackTrace();
        Channel channel = e.getChannel();
        channel.close();
        super.exceptionCaught(ctx, e);
    }
}
